<template>
  <div class="score-list">
    <el-row :gutter="10">
      <el-col :span="21">
        <div class="business-score" :title="businessScore.chkitemName">
          <span>{{ businessScore.chkitemName }}</span>
          <span class="score-input">{{ businessScore.scoreInput }}分</span>
          <!--<dict-tag class="m-l-sm" :options="dict.type.cq_eval_score_level" :value="businessScore.scoreLevel" />-->
          <!--<dict-tag class="m-l-sm" :options="dict.type.cq_eval_result" :value="businessScore.scoreResult" />-->
          <el-dropdown @command="commandChange($event, businessScore, 'scoreLevel')" trigger="click">
            <dict-tag class="m-l-sm" :options="dict.type.cq_eval_score_level" :value="businessScore.scoreLevel" />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="dictItem in dict.type.cq_eval_score_level" :key="'scoreLevel'+dictItem.value" :command="dictItem.value">{{ dictItem.label }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown @command="commandChange($event, businessScore, 'scoreResult')" trigger="click">
            <dict-tag class="m-l-sm" :options="dict.type.cq_eval_result" :value="businessScore.scoreResult" />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="dictItem in dict.type.cq_eval_result" :key="'scoreResult'+dictItem.value" :command="dictItem.value">{{ dictItem.label }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-col>
      <el-col :span="3">
        <el-popover v-if="businessScore.inputMode === CQ_EVAL_INPUT_MODE.OPTION" placement="left" width="200" trigger="click" v-model="showOptList">
          <el-button slot="reference" size="mini" type="primary" @click="selected = []" style="margin-bottom: 10px;">添加检查项</el-button>
          <el-empty :image-size="50" v-if="!allCheckItemList.length" />
          <div class="opt-list-wrap" v-else>
            <div class="opt-list">
              <div
                class="opt-item ellipsis"
                v-for="item in allCheckItemList"
                :key="item.chkitemCode"
                :title="item.chkitemName"
                :class="{
                  selected: selected.includes(item.chkitemCode),
                  disabled: selectedCodes.includes(item.chkitemCode)
                }"
                @click="selectItem(item)"
              >
                {{ item.chkitemName }}
              </div>
            </div>
            <div class="btn">
              <el-button size="mini" type="primary" :disabled="!selected.length" @click="addItem">添加 {{ selected.length }}/{{ allCheckItemList.length - selectedCodes.length }}</el-button>
            </div>
          </div>
        </el-popover>
      </el-col>
    </el-row>
    <div class="line" />
    <el-row :gutter="10">
      <el-col :span="6" v-for="(item, index) in checkItemList" :key="'form' + item.chkitemId">
        <div class="item">
          <div class="lable-title">
            <span><span style="color: red;">*</span>{{ item.chkitemName }}<span class="tip">减分带负号(-)</span></span>
            <el-popconfirm v-if="businessScore.inputMode==CQ_EVAL_INPUT_MODE.OPTION" title="移除此检查项？" confirm-button-text="移除" @confirm="removeCheckItem(index)">
              <i slot="reference" class="el-icon-close btn-remove pointer" />
            </el-popconfirm>
            <!--<el-checkbox v-else v-model="item.noCheck" @change="noCheckChange(item)">
              <span style="font-size: 12px;">
                甩项
              </span>
            </el-checkbox>-->
          </div>
          <div class="custom-form-item el-input-group el-input-group--append">
            <el-input-number v-model="item.scoreInput" :disabled="RESULT.THROWTERM == item.scoreResult" placeholder="负分数,例：-7" :min="-100" :precision="2" :controls="false" :max="0" class="score-value" @input="$forceUpdate()" @change="scoreChange(item)" />
            <div class="el-input-group__append append-unit">分</div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getProTradeType } from '@/api/checkScore/projectScore'
import { CQ_EVAL_INPUT_MODE, CQ_EVAL_RDC_TYPE, CQ_EVAL_RESULT_ENUM as RESULT } from '@/utils/baseData'
import { matchingRule } from '../chkitemScore/common'
export default {
  name: 'ScoreList',
  props: {
    projectId: {
      type: String,
      default: () => ''
    }
  },
  dicts: ['cq_eval_score_level', 'cq_eval_result'],
  data() {
    return {
      CQ_EVAL_INPUT_MODE,
      CQ_EVAL_RDC_TYPE,
      RESULT,
      uploading: false,
      query: {},
      selected: [],
      removeItemList: [],
      showOptList: false,
      allCheckItemList: [],
      checkItemList: [],
      businessScore: {
        scoreLevel: '',
        scoreInput: '',
        scoreResult: ''
      }
    }
  },
  computed: {
    selectedCodes() {
      const list = this.checkItemList || []
      return list.map(i => i.chkitemCode)
    }
  },
  watch: {
    projectId() {
      // this.tradeFilter()
    }
  },
  created() { // 初始化
    this.query = this.$route.query
  },
  mounted() {
  },
  methods: {
    // 合格状态改变
    commandChange(command, item, key) {
      item[key] = command
      this.$forceUpdate()
    },
    scoreChange(obj) {
      if (!/^((\-[1-9]{1}\d*)(\.\d{1,2})?|(0{1}))$/.test(obj.scoreInput)) {
        if (Number(obj.scoreInput)) {
          if (obj.scoreInput > 0) {
            this.$message({ message: '扣分项取值范围 -100 ~ 0数字。', type: 'warning', duration: 5000 })
            obj.scoreInput = null
            this.$forceUpdate()
            return
          } else {
            obj.scoreInput = parseFloat(obj.scoreInput.toFixed(2))
          }
        } else {
          obj.scoreInput = null
          this.$forceUpdate()
          return
        }
      }
      if (obj.scoreInput < -100) {
        this.$message({ message: '扣分项请输入范围 -100 ~ 0数字。', type: 'warning', duration: 5000 })
        obj.scoreInput = null
        return
      }
      this.calculateScore()
    },
    calculateScore() {
      let reduceScore = 0
      for (let i = 0; i < this.checkItemList.length; i++) {
        if (this.checkItemList[i].scoreInput) {
          reduceScore += parseFloat(this.checkItemList[i].scoreInput)
        }
      }
      this.businessScore.scoreInput = Math.round((100 + reduceScore) * 100) / 100
      this.businessScore.scoreLevel = matchingRule({rule: this.businessScore.levelStdd, value: this.businessScore.scoreInput, type: 'number'})
      this.businessScore.scoreResult = matchingRule({rule: this.businessScore.resultStdd, value: this.businessScore.scoreInput, type: 'number'})
      this.$forceUpdate()
    },
    init (row, cfgInfo) {
      row = JSON.parse(JSON.stringify(row))
      cfgInfo = JSON.parse(JSON.stringify(cfgInfo))
      const self = this
      this.businessScore = {
        scoreLevel: '',
        scoreInput: '',
        scoreResult: ''
      }
      if (cfgInfo.children && cfgInfo.children.length > 0) {
        for (let i = 0; i < cfgInfo.children.length; i++) {
          if (cfgInfo.chkitemId === cfgInfo.children[i].parentId) {
            Object.assign(this.businessScore, cfgInfo.children[i])
            this.businessScore.scoreInput = 100
            this.businessScore.scoreLevel = 'A'
            this.businessScore.scoreResult = RESULT.EXCELLENT
          }
        }
      }
      this.allCheckItemList = cfgInfo.children.filter(child => child.parentId !== cfgInfo.chkitemId)
      this.allCheckItemList.forEach(item => {
        item.noCheck = false
        item.isDelete = 0
        item.scoreInput = null
      })
      if (CQ_EVAL_INPUT_MODE.OPTION === this.businessScore.inputMode) {
        this.checkItemList = []
      } else {
        this.checkItemList = [...this.allCheckItemList]
      }
      if (row) {
        handleEdit(row)
      }
      // this.tradeFilter()
      // 处理编辑初始化数据
      function handleEdit (row) {
        const list = [...self.allCheckItemList]
        if (row.scores && row.scores.length > 0) {
          for (let i = 0; i < list.length; i++) {
            for (let j = 0; j < row.scores.length; j++) {
              if (row.scores[j].chkitemCode === list[i].chkitemCode) {
                list[i].noCheck = row.scores[j].scoreResult === RESULT.THROWTERM
                list[i].scoreInput = row.scores[j].scoreInput
                list[i].scoreResult = row.scores[j].scoreResult
                list[i].chkitemScoreId = row.scores[j].chkitemScoreId
              }
              if (row.scores[j].chkitemCode === self.businessScore.chkitemCode) {
                self.businessScore.chkitemScoreId = row.scores[j].chkitemScoreId
                self.businessScore.scoreInput = row.scores[j].scoreInput
                self.businessScore.scoreLevel = row.scores[j].scoreLevel
                self.businessScore.scoreResult = row.scores[j].scoreResult
              }
            }
          }
          if (self.businessScore.inputMode === CQ_EVAL_INPUT_MODE.OPTION) {
            self.checkItemList = list.filter(item => row.scores.some(score => score.chkitemCode === item.chkitemCode))
          } else {
            self.checkItemList = list
          }
        }
      }
    },
    // 操盘 过滤
    async tradeFilter () {
      if (this.projectId) {
        const response = await getProTradeType({ projectId: this.projectId }).catch(() => false)
        if (response.code === 200) {
          const tradeType = response.data
          if (!tradeType) {
            this.$message.warning('项目不属于操盘与非操盘')
          }
          this.checkItemList = this.checkItemList.filter(item => item.tradeType.split(',').some(trade => trade === tradeType))
        }
      }
    },
    getValidate() {
      let validate = false
      if (this.checkItemList.length > 0) {
        validate = this.checkItemList.every(item => (item.scoreInput || item.scoreInput === 0) || item.scoreResult === RESULT.THROWTERM)
      } else {
        validate = true
      }
      if (!validate) {
        this.$message.warning('检查项，每项必填。')
      }
      return validate
    },
    getData() {
      const scores = []
      const list = [...this.checkItemList]
      this.removeItemList.forEach(item => {
        if (!list.some(listItem => listItem.chkitemCode === item.chkitemCode) && item.chkitemScoreId) {
          list.push(item)
        }
      })
      list.forEach(item => {
        scores.push({
          chkitemCfgId: item.cfgId,
          chkitemScoreId: item.chkitemScoreId,
          versionCode: item.itemVersionCode,
          scoreInput: item.scoreInput,
          scoreResult: item.scoreResult,
          scoreType: item.scoreType,
          dataType: item.dataType,
          chkitemCode: item.chkitemCode,
          isDelete: item.isDelete
        })
      })
      this.businessScore.chkitemCfgId = this.businessScore.cfgId
      this.businessScore.versionCode = this.businessScore.itemVersionCode
      scores.push({...this.businessScore})
      return scores
    },
    noCheckChange(item) {
      if (item.noCheck) {
        item.scoreInput = ''
        item.scoreResult = RESULT.THROWTERM
      } else {
        item.scoreResult = ''
      }
      this.calculateScore()
    },
    selectItem(item) {
      const { selected } = this
      const code = item.chkitemCode
      const index = selected.findIndex(i => i === code)
      if (index > -1) selected.splice(index, 1)
      else selected.push(code)
    },
    addItem() {
      const { allCheckItemList, selected, checkItemList } = this
      this.showOptList = false
      // const isExist = checkItemList.find(i => i.chkitemCode === selected)
      // if (isExist) return this.$message('该检查项已存在')

      const arr = allCheckItemList.filter(i => selected.includes(i.chkitemCode))
      checkItemList.push(...arr)
      this.selected = []
      this.calculateScore()
    },
    removeCheckItem(index) {
      this.checkItemList[index].isDelete = 1
      this.removeItemList.push(this.checkItemList[index])
      this.checkItemList.splice(index, 1)
      this.calculateScore()
    }
  }
}
</script>

<style scoped lang='scss'>
  $lineColor: #dddddd;
  .score-list {
    border: 1px solid $lineColor;
    border-radius: 5px;
    padding: 16px;
  }
  .line {
    margin: 0 -16px;
    margin-bottom: 16px;
    border-bottom: 1px solid $lineColor;
    height: 1px;
  }
  .business-score {
    margin-bottom: 16px;
    .score-input {
      margin-left: 10px;
    }
    .m-l-sm {
      display: inline-block;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .opt-list-wrap {
    margin: 0 -12px;
    .opt-list {
      max-height: 300px;
      overflow-y: auto;
    }
    .opt-item {
      font-size: 12px;
      padding: 0 40px 0 20px;
      color: #606266;
      line-height: 34px;
      cursor: pointer;
      &:hover {
        background-color: #f5f7fa;
      }
    }
    .selected {
      color: #409eff;
      font-weight: 700;
      &::after {
        position: absolute;
        right: 20px;
        font-family: 'element-icons';
        content: '\e6da';
        font-size: 12px;
      }
    }
    .disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    .btn {
      text-align: right;
      padding: 10px 20px 0;
    }
  }
  .item {
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(black, 0.1);
    margin-bottom: 10px;
    padding: 0 0 10px 20px;
    .lable-title {
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #ebeef5;
      padding: 10px 10px 5px;
      margin:0 0 10px -20px;
      .tip {
        margin-left: 6px;
        font-size: 12px;
        color: #999;
      }
      .btn-remove {
        padding: 3px;
        &:hover {
          color: #409eff;
        }
      }
    }
    .custom-form-item {
      margin-top: 10px;
      padding-right: 60px;
      .score-result {
        margin-right: 20px;
        flex: 1;
        text-align: right;
      }
    }
    .score-value{
      width: 140px;
    }
  }
</style>
